// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object"){ // CommonJS
    mod(require("../../lib/codemirror"));
  } else if (typeof define == "function" && define.amd){ // AMD
    define(["../../lib/codemirror"], mod);
  } else { // Plain browser env
    mod(CodeMirror);
  }
})(function(CodeMirror) {
"use strict";

  CodeMirror.registerHelper("fold", "region", function(cm, start) {
    let lineNo = start.line;
    let line   = cm.getLine(lineNo);
    if(!line || !line.match(/\/\/[ |\t]*#region/)){
      return undefined;
    }
    let startPoint = line.length;
    let level = 1;
    let lastLineNo  = cm.lastLine();
    while(lineNo<lastLineNo){
      lineNo++;
      line = cm.getLine(lineNo);
      if(!line){continue;}
      if(line.match(/\/\/[ |\t]*#endregion/)){
        if(level==1){
          break;
        }else{
          level--;
        }
      }
      if(line.match(/\/\/[ |\t]*#region/)){
        level++;
      }
    }
    return {
      from: CodeMirror.Pos(start.line, startPoint),
      to: CodeMirror.Pos(lineNo, line.length)
    };
  });

});
